package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;



    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //用于存放begin到end的所有日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String joinDateList = StringUtils.join(dateList, ",");//2023-03-01,2023-03-02,2023-03-03



        //每天营业额集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//2023-03-01 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//2023-03-01 23:59:59

            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }
        String jointurnoverList = StringUtils.join(turnoverList, ",");//100,200,300

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(joinDateList);
        turnoverReportVO.setTurnoverList(jointurnoverList);


        return turnoverReportVO;
    }


    /**
     * 指定时间区间内用户数量统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //用于存放begin到end的所有日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);//2023-03-01

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//2023-03-02
            dateList.add(begin);
        }

        //每日新增用户集合
        List<Integer> newUserList = new ArrayList<>();
        //每日总用户集合
        List<Integer> totalUserList = new ArrayList<>();

        //遍历日期集合
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//2023-03-01 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//2023-03-01 23:59:59

            //查询总用户数量
            Map map = new HashMap();
            map.put("end",endTime);
            Integer totalUser = userMapper.countByMap(map);

            //查询新增用户数量
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        String joinDateList = StringUtils.join(dateList, ",");//2023-03-01,2023-03-02
        String joinTotalUserList = StringUtils.join(totalUserList, ",");//100,200
        String joinNewUserList = StringUtils.join(newUserList, ",");//100,200

        //封装结果数据
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(joinDateList);
        userReportVO.setTotalUserList(joinTotalUserList);
        userReportVO.setNewUserList(joinNewUserList);

        return userReportVO;
    }



    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //用于存放begin到end的所有日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        String joinDateList = StringUtils.join(dateList, ",");//2023-03-01,2023-03-02,2023-03-03

        //每日订单数量集合
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数量集合
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer OrderCount = orderMapper.countByMap(map);
            orderCountList.add(OrderCount);

            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);


        }

        String joinOrderCountList = StringUtils.join(orderCountList, ",");//100,200,300
        String joinValidOrderCountList = StringUtils.join(validOrderCountList, ",");//100,200,300

        //计算总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算有效订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //封装结果数据
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(joinDateList);
        orderReportVO.setOrderCountList(joinOrderCountList);
        orderReportVO.setValidOrderCountList(joinValidOrderCountList);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        return orderReportVO;
    }


    /**
     * 销售top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //获取商品名称集合
        List<String> names = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : salesTop10) {
            names.add(goodsSalesDTO.getName());
        }
        String nameList = StringUtils.join(names, ",");
        //获取销量集合
        List<Integer> numbers = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : salesTop10) {
            numbers.add(goodsSalesDTO.getNumber());
        }
        String numberList = StringUtils.join(numbers, ",");

       /* //获取商品名称集合
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        //获取销量集合
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");*/



        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameList);
        salesTop10ReportVO.setNumberList(numberList);

        return salesTop10ReportVO;
    }


    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1.获取查询营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);//2023-02-03
        LocalDate dateEnd = LocalDate.now().minusDays(1);//2023-03-02

        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);//2023-02-03 00:00:00
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);//2023-03-02 23:59:59

        //调用service获取营业数据
        BusinessDataVO businessDataVO = workspaceService.businessData(begin, end);

        //2.根据查询到的数据，写入excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");//获取模板文件

        try {
            //创建excel对象
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取sheet
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //写入时间数据
            sheet.getRow(1).getCell(1).setCellValue("时间"+dateBegin + "至" + dateEnd);
            //写入概览数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());//营业额
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());//订单完成率
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());//新增用户数

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());//有效订单数
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());//单品销售总额


            //写入明细数据
            for (int i=0;i<30;i++){
                LocalDate date = dateBegin.plusDays(i);//2023-02-03
                LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//2023-02-03 00:00:00
                LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//2023-02-03 23:59:59
                BusinessDataVO businessData = workspaceService.businessData(beginTime, endTime);//获取数据

                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());//日期

                row.getCell(2).setCellValue(businessData.getTurnover() == null ? 0 : businessData.getTurnover());//营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount());//有效订单数
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice());//平均客单价
                row.getCell(6).setCellValue(businessData.getNewUsers());//新增用户数
            }

            //3.输出流将excel文件下载到浏览器
            ServletOutputStream out = response.getOutputStream();//获取输出流
            excel.write(out);//写入excel

            //关闭
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }





    }
}
